package com.utry.license.server.api;

import com.utry.license.common.base.BaseResult;
import com.utry.license.common.base.ErrorEnum;
import com.utry.license.common.base.ErrorUtil;
import com.utry.license.server.dto.LicenseCreateDTO;
import com.utry.license.server.license.LicenseConfigBean;
import com.utry.license.server.license.LicenseCreator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
 * @description 证书相关接口
 *
 * @author renxin
 *
 * @email renxinzhiliangzhi@163.com
 * 
 * @date 2019/7/25 15:20
 */
@Api(tags = "证书服务端接口")
@Slf4j
@RequestMapping("license")
@RestController
public class LicenseApi {

    @Autowired
    private LicenseCreator licenseCreator;

    @Autowired
    private LicenseConfigBean configBean;

    @Autowired
    private HttpServletResponse response;

    @ApiOperation("携带扩展参数的授权证书创建")
    @PostMapping(value = "create",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResult createLicense(@Validated @RequestBody LicenseCreateDTO dto) throws Exception{

        byte[] licenseBytes = licenseCreator.createLicense(dto);
        // 将文件写出
        write2Response(licenseBytes);

        return BaseResult.build();
    }

    /**
     * 下载证书文件
     *
     * @param licenseBytes
     */
    private void write2Response(byte[] licenseBytes){

        String fileName = configBean.getLicenseFileName();
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

        try(OutputStream outputStream = response.getOutputStream()){
            outputStream.write(licenseBytes);
        }catch (IOException e){

            log.error("证书文件写出失败",e);
            throw ErrorUtil.buildBaseException(ErrorEnum.LICENSE_DOWNLOAD_ERROR);
        }

    }

}
